package com.ejuornal.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.ejuornal.bean.Ads;
import com.ejuornal.service.AdsPosService;
import com.ejuornal.service.AdsService;
import com.ejuornal.springutil.SpringUtil;
import com.ejuornal.util.StrToIntArray;
import com.ejuornal.util.UploadUtil;
import com.google.gson.Gson;

public class AdsAction extends BaseAction<Ads>{

	private static final long serialVersionUID = 1L;
	private AdsService adsService;
	private AdsPosService adsPosService;
	private Ads ads = null;
	private String adsId=null;
	private Ads adsInfo = null;//广告详情信息
	private String adsIdStr = null;//广告详情信息id
	private String value;
	
	private File upload;//上传文件
	private String uploadFileName;//上传文件名
	private String uploadContentType;
	
	/**
	 * 描述：得到所有的分页 数据
	 * @return Page<list>
	 */
	public String getAllAds(){
		String url = "admin/findAllAds";
		pages = adsService.findAll((page - 1)*10, url);
		return SUCCESS;
	}
	/**
	 * 描述：添加广告
	 * @return
	 */
	public String addAds()
	{
	    String beginDate = (String) super.getRequestParameter("beginDate");
        String endDate = (String) super.getRequestParameter("endDate");
        Date beginDate1 = null;
        Date endDate2 = null;
        try {
            beginDate1 = new SimpleDateFormat("yyyy-MM-dd").parse(beginDate);
            endDate2 = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
        } catch (ParseException e) {
            return INPUT;
        }
        if(endDate2.compareTo(beginDate1) > 0)  {
            ads.setBeginDate(beginDate1);
            ads.setEndDate(endDate2);
            String adsUrl = ads.getUrl();
            if(adsUrl.startsWith("www")) {
            	adsUrl = "http://" + adsUrl;
            	ads.setUrl(adsUrl);
            }
            
            ads.setPicSrc(UploadUtil.upload(upload, uploadFileName));
            adsService.add(ads);
            return "addAdsList";
        } else {
            return INPUT;
        }
	}
	
	/**
	 * 描述：删除广告
	 * @return
	 */
	public String deleteAds()
	{
		adsService.delete(StrToIntArray.ChangeStrToIntArray(adsId));
		return "deleteAdsList";
	}
	/**
	 * 描述：根据广告位置查询所有广告位
	 * @return page<Ads>
	 */
	public String findByAdsPos()
	{
		adsService = (AdsService) SpringUtil.getBean("adsService");
		String url = "admin/findAllAds";
		pages = adsService.findByAdsPosId((page - 1)*10, url, ads.getAdsPosId());
		return "adsListByAdsPos";
	}
	
	/**
	 * 根据ID查询广告信息
	 * @author syb
	 * @return ads
	 */
	public String findById() {
		ads = adsService.findByAdsId(Integer.parseInt( adsIdStr));
		
		if("".equals(ads.getPicSrc()) || ads.getPicSrc() == null) {
			ads.setPicSrc("images/03.gif");
		}
		
		if("1".equals(value)) {
			return "change";
		} else if("2".equals(value)) {
			Gson gson = new Gson();
			String adsStr = gson.toJson(ads);
			HttpServletResponse res = ServletActionContext.getResponse();   
			res.reset();   
			res.setContentType("text/html;charset=utf-8");   
			PrintWriter pw;
			try {
				pw = res.getWriter();
				pw.print(adsStr);
				pw.flush();   
				pw.close();  
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return "userLogin";
		} else {
			return "error";
		}
	}
	
	/**
	 * 描述：广告详情
	 * @return Ads
	 */
	public String detailAds(){
		adsService = (AdsService) SpringUtil.getBean("adsService");
		adsInfo = adsService.findByAdsVOId(Integer.parseInt( adsIdStr));
		
		if("1".equals(value)) {
			return "change";
		} else if("2".equals(value)) {
			Gson gson = new Gson();
			String adsStr = gson.toJson(adsInfo);
			HttpServletResponse res = ServletActionContext.getResponse();   
			res.reset();   
			res.setContentType("text/html;charset=utf-8");   
			PrintWriter pw;
			try {
				pw = res.getWriter();
				pw.print(adsStr);
				pw.flush();   
				pw.close();  
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return "userLogin";
		}
		
		return"detailInfo";
	}
	
	/**
	 * 描述：读取数据到修改页面
	 * 作者：lwf
	 * @return Ads
	 */
	public String updateAdsInfo(){
		adsService = (AdsService) SpringUtil.getBean("adsService");
		adsInfo = adsService.findByAdsId(Integer.parseInt(adsIdStr));
		return "updateAdsInfo";		
	}
	/**
	 * 描述：更新广告数据到数据库
	 * 作者：lwf
	 * @return
	 */
	public String updateAds(){
		adsIdStr = String.valueOf(ads.getAdsId());
	    String beginDate = (String) super.getRequestParameter("beginDate");
        String endDate = (String) super.getRequestParameter("endDate");
        Date beginDate1 = null;
        Date endDate2 = null;
        try {
            beginDate1 = new SimpleDateFormat("yyyy-MM-dd").parse(beginDate);
            endDate2 = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
        } catch (ParseException e) {
        }
        if(endDate.compareTo(beginDate) > 0) {
        	//图片重命名，并存到数据库
            String realPath = ServletActionContext.getServletContext().getRealPath("/attached/images");
            String dbPicSrc = null;//存储路径
            if(upload != null){
                File saveDir = new File(realPath);
                //图片重命名
                String ext = uploadFileName.split("\\.")[1];//后缀名
                Calendar cal = Calendar.getInstance();
                String reName = String.valueOf(cal.getTimeInMillis());
                dbPicSrc = "attached/images/"+reName+"."+ext;
                uploadFileName = reName+"."+ext;
                
                if(saveDir.exists()){
                    File saveFile = new File(saveDir, uploadFileName);
                    try {
                        FileUtils.copyFile(upload, saveFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                else{
                    saveDir.mkdirs();
                    File saveFile = new File(saveDir, uploadFileName);
                    try {
                        FileUtils.copyFile(upload, saveFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            ads.setBeginDate(beginDate1);
            ads.setEndDate(endDate2);
            ads.setPicSrc(dbPicSrc);
    		adsService.update(ads);
        }else{
        	 return INPUT;
        }
        
		return "updGetAllAds";
	}
	
	
	public String updateLoginImg() {
	    String imgUrl = (String) super.getRequestParameter("imgUrl");
	    if(adsService.updateLoginImg(imgUrl)) {
	        return SUCCESS;
	    }
	    return INPUT;
	}
	
	
	public AdsPosService getAdsPosService() {
		return adsPosService;
	}
	public void setAdsPosService(AdsPosService adsPosService) {
		this.adsPosService = adsPosService;
	}
	public String getAdsIdStr() {
		return adsIdStr;
	}
	public void setAdsIdStr(String adsIdStr) {
		this.adsIdStr = adsIdStr;
	}
	public Ads getAdsInfo() {
		return adsInfo;
	}
	public void setAdsInfo(Ads adsInfo) {
		this.adsInfo = adsInfo;
	}
	public String getAdsId() {
		return adsId;
	}
	public void setAdsId(String adsId) {
		this.adsId = adsId;
	}
	public Ads getAds() {
		return ads;
	}

	public void setAds(Ads ads) {
		this.ads = ads;
	}

	public AdsService getAdsService(){
		return adsService;
	}
	@Resource(name="adsService")
	public void setAdsService(AdsService adsService){
		this.adsService = adsService;
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	
}
